package org.example.wumeng.service.impl;

import org.example.wumeng.mapper.T_bookMapper;
import org.example.wumeng.service.T_bookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.example.wumeng.pojo.Book;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class T_bookServiceImpl implements T_bookService {

    @Autowired
    private T_bookMapper bookMapper;

    @Override
    public Map<String, Object> getList(Integer page, Integer size, String title, String author, String category) {
        // 参数验证和默认值设置
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1) {
            size = 10;
        }
        if (size > 100) { // 限制最大查询数量
            size = 100;
        }

        // 计算偏移量
        int offset = (page - 1) * size;

        try {
            // 查询数据
            List<Book> books = bookMapper.selectWithCondition(title, author, category, offset, size);
            Long total = bookMapper.countWithCondition(title, author, category);

            // 构造返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("data", books);
            result.put("total", total);
            result.put("page", page);
            result.put("size", size);
            result.put("pages", (total + size - 1) / size);

            return result;
        } catch (Exception e) {
            throw new RuntimeException("查询医书列表失败: " + e.getMessage());
        }
    }

    @Override
    public Book getById(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("医书ID不能为空或无效");
        }

        try {
            Book book = bookMapper.selectById(id);
            if (book == null) {
                throw new RuntimeException("医书不存在");
            }
            return book;
        } catch (Exception e) {
            throw new RuntimeException("查询医书详情失败: " + e.getMessage());
        }
    }

    @Override
    public String getFullContentById(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("医书ID不能为空或无效");
        }

        try {
            // 先检查医书是否存在
            Book book = bookMapper.selectById(id);
            if (book == null) {
                throw new RuntimeException("医书不存在");
            }

            // 获取全文内容
            String fullContent = bookMapper.selectFullContentById(id);
            return fullContent;
        } catch (Exception e) {
            throw new RuntimeException("获取医书全文内容失败: " + e.getMessage());
        }
    }

    @Override
    public Long create(Book book) {
        if (book == null) {
            throw new IllegalArgumentException("医书信息不能为空");
        }
        if (!StringUtils.hasText(book.getTitle())) {
            throw new IllegalArgumentException("书名不能为空");
        }
        if (!StringUtils.hasText(book.getAuthor())) {
            throw new IllegalArgumentException("作者不能为空");
        }
        if (!StringUtils.hasText(book.getCategory())) {
            throw new IllegalArgumentException("分类不能为空");
        }

        try {
            // 设置创建时间
            book.setCreateTime(LocalDateTime.now());
            book.setUpdateTime(LocalDateTime.now());

            int result = bookMapper.insert(book);
            if (result <= 0) {
                throw new RuntimeException("创建医书失败");
            }

            return book.getId();
        } catch (Exception e) {
            throw new RuntimeException("创建医书失败: " + e.getMessage());
        }
    }

    @Override
    public void update(Long id, Book book) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("医书ID不能为空或无效");
        }
        if (book == null) {
            throw new IllegalArgumentException("医书信息不能为空");
        }

        try {
            // 检查医书是否存在
            Book existingBook = bookMapper.selectById(id);
            if (existingBook == null) {
                throw new RuntimeException("医书不存在");
            }

            // 设置更新时间
            book.setId(id);
            book.setUpdateTime(LocalDateTime.now());

            int result = bookMapper.updateById(book);
            if (result <= 0) {
                throw new RuntimeException("更新医书失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("更新医书失败: " + e.getMessage());
        }
    }

    @Override
    public void delete(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("医书ID不能为空或无效");
        }

        try {
            // 检查医书是否存在
            Book existingBook = bookMapper.selectById(id);
            if (existingBook == null) {
                throw new RuntimeException("医书不存在");
            }

            int result = bookMapper.deleteById(id);
            if (result <= 0) {
                throw new RuntimeException("删除医书失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("删除医书失败: " + e.getMessage());
        }
    }

    @Override
    public Long countByAuthor(String author) {
        if (!StringUtils.hasText(author)) {
            throw new IllegalArgumentException("作者不能为空");
        }

        try {
            return bookMapper.countWithCondition(null, author.trim(), null);
        } catch (Exception e) {
            throw new RuntimeException("统计医书数量失败: " + e.getMessage());
        }
    }

    @Override
    public Long countByCategory(String category) {
        if (!StringUtils.hasText(category)) {
            throw new IllegalArgumentException("分类不能为空");
        }

        try {
            return bookMapper.countWithCondition(null, null, category.trim());
        } catch (Exception e) {
            throw new RuntimeException("统计医书数量失败: " + e.getMessage());
        }
    }

    @Override
    public org.example.wumeng.pojo.Result<java.util.List<Book>> getByCategory(String category, int page, int size) {
        try {
            if (!StringUtils.hasText(category)) {
                return org.example.wumeng.pojo.Result.badRequest("分类不能为空");
            }

            int offset = (page - 1) * size;
            List<Book> books = bookMapper.selectByCategory(category.trim(), offset, size);
            return new org.example.wumeng.pojo.Result<>(200, "查询成功", books, null);

        } catch (Exception e) {
            return org.example.wumeng.pojo.Result.error("查询分类医书失败: " + e.getMessage());
        }
    }

    @Override
    public org.example.wumeng.pojo.Result<java.util.List<java.util.Map<String, Object>>> getCategoryStatistics() {
        try {
            List<java.util.Map<String, Object>> statistics = bookMapper.getCategoryStatistics();
            return new org.example.wumeng.pojo.Result<>(200, "获取成功", statistics, null);
        } catch (Exception e) {
            return org.example.wumeng.pojo.Result.error("获取分类统计失败: " + e.getMessage());
        }
    }
}